from fastapi import APIRouter, HTTPException, Depends
from typing import Optional
from crud.user_center.Recipe import add_recipe, get_user_recipes, delete_recipe, update_recipe
from routers.user import get_current_user_id
from pydantic import BaseModel

router = APIRouter(tags=["食谱管理"])

class RecipeInput(BaseModel):
    dish_name: str
    ingredients: str
    instructions: str

# 添加食谱
@router.post("/recipes")
async def add_recipe_route(recipe: RecipeInput, user_id: str = Depends(get_current_user_id)):
    """
    添加食谱
    :param recipe: 食谱数据
    :param user_id: 当前用户 ID
    :return: 添加结果
    """
    try:
        result = add_recipe(user_id, recipe.dish_name, recipe.ingredients, recipe.instructions)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# 获取用户食谱列表
@router.get("/recipes")
async def get_recipes_route(user_id: str = Depends(get_current_user_id)):
    """
    获取用户的食谱列表
    :param user_id: 当前用户 ID
    :return: 用户的食谱列表
    """
    try:
        recipes = get_user_recipes(user_id)
        if recipes is None:
            raise HTTPException(status_code=404, detail="未找到食谱记录")
        return {"recipes": recipes}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# 删除食谱
@router.delete("/recipes/{recipe_id}")
async def delete_recipe_route(recipe_id: int, user_id: str = Depends(get_current_user_id)):
    """
    删除食谱
    :param recipe_id: 食谱 ID
    :param user_id: 当前用户 ID
    :return: 删除结果
    """
    try:
        result = delete_recipe(recipe_id)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/recipes/{recipe_id}")
async def update_recipe_route(recipe_id: int, recipe: RecipeInput, user_id: str = Depends(get_current_user_id)):
    """
    修改食谱
    :param recipe_id: 食谱 ID
    :param recipe: 食谱数据
    :param user_id: 当前用户 ID
    :return: 修改结果
    """
    try:
        result = update_recipe(recipe_id, recipe.dish_name, recipe.ingredients, recipe.instructions)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))